package com.ddh.bankmanager.aop;


import com.ddh.bankmanager.annotation.AuthCheck;
import com.ddh.bankmanager.constant.UserConstant;
import com.ddh.bankmanager.domain.customerinfo.CustomerInfo;
import com.ddh.bankmanager.enum_.RoleEnum;
import com.ddh.bankmanager.service.CustomerInfoService;
import com.ddh.bankmanager.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class AuthInterceptor {

    @Resource
    private CustomerInfoService customerInfoService;

    @Around("@annotation(authCheck)")
    public void doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        log.info("==========开始校验权限==========");
        //这个是从接口中获取该接口所需要什么权限来进行判断的
        String mustRole = authCheck.mustRole();
        //如果不需要权限就放行
        if (mustRole == null){
            log.info("==========不需要权限==========");
        }
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        Integer customerId = ThreadLocalUtil.get("customerId");
        log.info("用户id:{}", customerId);
        if (customerId == null) {
            log.info("==========用户未登录==========");
            throw new RuntimeException("用户未登录");
        }
        CustomerInfo customerInfo = customerInfoService.getCustomerInfoById(customerId);
        if (customerInfo == null){
            throw new RuntimeException("用户不存在");
        }
        String role = customerInfo.getRole();
        if (mustRole.equals(UserConstant.ADMIN_ROLE) && !mustRole.equals(role)){
            throw new RuntimeException("权限不足");
        }
        log.info("==========放行==========");
        joinPoint.proceed();
    }

}
